<template>
  <div class="registration-page">
    <!-- 顶部搜索栏 -->
    <div class="search-header">
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button
            @click="goBack"
            :icon="ArrowLeft"
            text
            class="back-btn"
        >
          返回
        </el-button>
      </div>
      <div class="search-box">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索机构名称"
            class="search-input"
            @keyup.enter="handleSearch"
            clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="my-records" @click="handleViewRecords">
        我的挂号记录
        <el-icon><ArrowRight /></el-icon>
      </div>
    </div>

    <!-- 医院列表 -->
    <div class="hospital-list">
      <div class="list-title">机构信息</div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="4" animated />
      </div>

      <!-- 机构列表 -->
      <div v-else class="hospital-cards">
        <div
            v-for="hospital in hospitalList"
            :key="hospital.hospitalId"
            class="hospital-card"
            @click="handleRegister(hospital)"
        >
          <div class="hospital-badge" :class="getLevelClass(hospital.grade)">
            {{ getLevelText(hospital.grade) }}
          </div>
          <div class="hospital-info">
            <div class="hospital-name">{{ hospital.hospitalName }}</div>
            <div class="hospital-level">机构等级：{{ getLevelText(hospital.grade) || '暂无等级信息' }}</div>
            <div class="hospital-address">
              <span class="address">{{ getFullAddress(hospital) }}</span>
            </div>
          </div>
          <div class="hospital-actions">
            <el-button type="primary" size="small" @click.stop="handleRegister(hospital)">
              立即挂号
            </el-button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="hospitalList.length === 0" class="empty-state">
          <el-empty description="暂无机构数据" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import { listHospital } from '@/api/institution/hospital.js'

const router = useRouter()

const searchKeyword = ref('')
const loading = ref(false)
const hospitalList = ref([])

// 返回函数 - 返回到 userdoctor 页面
const goBack = () => {
  router.push('/service/index')
}

// 页面加载时获取机构数据
onMounted(() => {
  loadHospitalData()
})

// 加载机构数据
const loadHospitalData = async () => {
  try {
    loading.value = true
    const response = await listHospital({
      pageNum: 1,
      pageSize: 10,
      hospitalName: searchKeyword.value || undefined
    })
    console.log('机构数据响应:', response)
    hospitalList.value = response.rows || response.data || []
    console.log('处理后的机构列表:', hospitalList.value)
  } catch (error) {
    console.error('加载机构数据失败:', error)
    ElMessage.error('加载机构数据失败')
    hospitalList.value = []
  } finally {
    loading.value = false
  }
}

// 获取完整地址
const getFullAddress = (hospital) => {
  if (!hospital) return '地址未知'

  const { province, city, district, address } = hospital
  const addressParts = []

  if (province) addressParts.push(province)
  if (city) addressParts.push(city)
  if (district) addressParts.push(district)
  if (address) addressParts.push(address)

  return addressParts.length > 0 ? addressParts.join('') : '地址未知'
}

// 获取机构等级对应的CSS类
const getLevelClass = (grade) => {
  if (!grade) return 'level-other'

  const gradeStr = grade.toString().toLowerCase()
  const levelMap = {
    '3a': 'level-3a',
    '三级甲等': 'level-3a',
    '三甲': 'level-3a',
    '2a': 'level-2a',
    '二级甲等': 'level-2a',
    '二甲': 'level-2a',
    '1a': 'level-1a',
    '一级甲等': 'level-1a',
    '一甲': 'level-1a',
  }
  return levelMap[gradeStr] || 'level-other'
}

// 获取机构等级显示文本
const getLevelText = (grade) => {
  if (!grade) return '医疗机构'

  const gradeStr = grade.toString()
  const levelTextMap = {
    '3a': '三甲',
    '三级甲等': '三甲',
    '2a': '二甲',
    '二级甲等': '二甲',
    '1a': '一甲',
    '一级甲等': '一甲',
    '3b': '三乙',
    '三级乙等': '三乙',
    '2b': '二乙',
    '二级乙等': '二乙',
    '1b': '一乙',
    '一级乙等': '一乙'
  }

  // 如果已经是中文等级名称，直接返回
  if (['三甲', '二甲', '一甲', '三乙', '二乙', '一乙', '三级甲等', '二级甲等', '一级甲等', '三级乙等', '二级乙等', '一级乙等'].includes(gradeStr)) {
    return gradeStr
  }

  return levelTextMap[gradeStr] || gradeStr || '医疗机构'
}

// 搜索处理
const handleSearch = () => {
  loadHospitalData()
}

// 查看挂号记录
const handleViewRecords = () => {
  ElMessage.info('查看挂号记录')
  // router.push('/medical/records')
}

// 立即挂号
const handleRegister = (hospital) => {
  router.push(`/medical/register/${hospital.hospitalId}`)
}
</script>

<style scoped lang="scss">
.registration-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 0;
}

// 顶部搜索栏
.search-header {
  background: white;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-bottom: 1px solid #f0f0f0;

  // 返回按钮样式
  .back-button {
    .back-btn {
      padding: 8px 12px;
      color: #409eff;
      font-size: 14px;
      border: none;

      &:hover {
        background-color: #f0f7ff;
        color: #79bbff;
      }
    }
  }

  .search-box {
    flex: 1;

    .search-input {
      :deep(.el-input__inner) {
        border-radius: 20px;
        background: #f5f5f5;
        border: none;
        height: 36px;
      }

      :deep(.el-input__prefix) {
        display: flex;
        align-items: center;
        margin-left: 8px;
      }
    }
  }

  .my-records {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
    color: #409eff;
    cursor: pointer;
    white-space: nowrap;

    &:hover {
      opacity: 0.8;
    }
  }
}

// 医院列表
.hospital-list {
  background: white;
  margin-top: 8px;

  .list-title {
    padding: 16px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
  }
}

// 加载状态
.loading-container {
  padding: 20px;
}

// 空状态
.empty-state {
  padding: 40px 0;
}

// 机构卡片容器
.hospital-cards {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

// 机构卡片
.hospital-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }

  .hospital-badge {
    position: absolute;
    top: 16px;
    right: 16px;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;

    &.level-3a {
      background: #fef0f0;
      color: #f56c6c;
      border: 1px solid #fbc4c4;
    }

    &.level-2a {
      background: #f0f9ff;
      color: #409eff;
      border: 1px solid #b3d8ff;
    }

    &.level-1a {
      background: #f0f9f0;
      color: #67c23a;
      border: 1px solid #c2e7b0;
    }

    &.level-other {
      background: #f5f5f5;
      color: #909399;
      border: 1px solid #dcdfe6;
    }
  }

  .hospital-info {
    .hospital-name {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;
      line-height: 1.4;
    }

    .hospital-level {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
      line-height: 1.4;
    }

    .hospital-address {
      display: flex;
      align-items: center;
      font-size: 13px;

      .address {
        color: #999;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .hospital-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .search-header {
    padding: 12px;
    flex-direction: row;
    gap: 8px;

    .back-button {
      .back-btn {
        padding: 6px 10px;
        font-size: 12px;
      }
    }

    .search-box {
      width: auto;
      flex: 1;
    }

    .my-records {
      align-self: center;
      font-size: 13px;
    }
  }

  .hospital-list .list-title {
    padding: 12px;
    font-size: 15px;
  }

  .hospital-cards {
    padding: 12px;
    gap: 12px;
  }

  .hospital-card {
    padding: 12px;

    .hospital-info {
      .hospital-name {
        font-size: 15px;
      }

      .hospital-level {
        font-size: 13px;
      }

      .hospital-address {
        font-size: 12px;
      }
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.hospital-card {
  animation: fadeIn 0.5s ease-out;
}
</style>